package org.example.filedemos;

import java.io.RandomAccessFile;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileChannelTest {

    private static final int BUFFER_SIZE = 1024;

    public static void main(String[] args) throws Exception{
        // 源文件
        URL url = FileChannelTest.class.getResource("/filedemos/1.txt");
        String filePath = url.getFile();
        RandomAccessFile raFile = new RandomAccessFile(filePath, "rw");
        FileChannel fChannel = raFile.getChannel();

        URL targetUrl = FileChannelTest.class.getResource("/filedemos/2.txt");
        RandomAccessFile targetFile = new RandomAccessFile(targetUrl.getFile(), "rw");
        FileChannel targetChannel = targetFile.getChannel();

        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);

        int num = -1;
        int outlength = -1;
        while ((num = fChannel.read(buffer)) > 0) {
            // 转成读模式
            buffer.flip();

            while ((outlength = targetChannel.write(buffer)) > 0) {
                System.out.println("写入的字节数=====>" + outlength);
            }

            // 重新转成写模式
            buffer.clear();
        }

        fChannel.close();
        targetChannel.close();
    }
}
